/*
 * BrushPack.java
 *
 * Created on January 8, 2008, 3:55 PM
 */

package picto.core;

import java.util.*;
import org.w3c.dom.*;
import picto.io.Archivable;
import picto.io.ArchiveException;
import picto.io.ArchiveReader;
import picto.io.ArchiveWriter;

/**
 *
 * @author davedes
 */
public class BrushPack implements Archivable, Iterable<Brush> {
    
    private String name;
    
    private List<Brush> brushes = new ArrayList<Brush>();
    private List<Brush> unmod = Collections.unmodifiableList(brushes);
    
    /**
     * Creates a new instance of BrushPack
     */
    public BrushPack(String name) {
        this.name = name;
    }
    
    public BrushPack() {
    }
    
    public Brush get(int i) {
        return brushes.get(i);
    }
    
    public Iterator<Brush> iterator() {
        return unmod.iterator();
    }
    
    public boolean add(Brush brush) {
        if (brush!=null)
            return brushes.add(brush);
        else
            return false;
    }
    
    public boolean remove(Brush brush) {
        if (brush!=null)
            return brushes.remove(brush);
        else
            return false;
    }
    
    public List<Brush> brushes() {
        return unmod;
    }
    
    public int size() {
        return brushes.size();
    }
        
    public void dispose() {
        for (int i=0; i<brushes.size(); i++) {
            ArchivableImage img = brushes.get(i).getTexture();
            if (img!=null)
                img.dispose();
        }
    }
    
    public void read(ArchiveReader reader, Element root) throws ArchiveException {
        if (!"brush-pack".equals(root.getNodeName()))
            throw new IllegalArgumentException("BrushPack must be parsed from <brush-pack> tag");
        
        String nameStr = root.getAttribute("name");
        name = nameStr.length()!=0 ? nameStr : null;
        
        brushes.clear();
        NodeList nl = root.getChildNodes();
        for (int i=0; i<nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n instanceof Element
                    && "brush".equals(n.getNodeName())) {
                Brush br = new Brush();
                br.read(reader, (Element)n);
                add(br);
            }
        }
    }
    
    public Element write(ArchiveWriter writer) throws ArchiveException {
        Document doc = writer.getDocument();
        Element root = doc.createElement("brush-pack");
        
        for (int i=0; i<brushes.size(); i++) {
            Brush b = brushes.get(i);
            if (b!=null) {
                try {
                    Element child = b.write(writer);
                    root.appendChild(child);
                } catch (ArchiveException exc) {
                    System.err.println("Cannot store brush '"+b.getName()+"' ");
                }                
            }
        }
        return root;
    }
}